<template>
  <div class='container'>
    <el-card class="box-card">
      <!-- 标题 -->
      <div
        slot="header"
        class="clearfix"
      >
        <span>{{showTitle}}</span>
      </div>
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="100px"
      >
        <!-- 学科(完成联动) -->
        <el-form-item
          label="学科:"
          prop="subjectID"
        >
          <el-select
            v-model="subjectName"
            placeholder="请选择"
            @change="getSubjectsInfo($event)"
          >
            <el-option
              v-for="item in subject"
              :key="item.value"
              v-model="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 目录(完成联动) -->
        <el-form-item
          prop="catalogID"
          label="目录:"
        >
          <el-select
            v-model="catalogName"
            placeholder="请选择"
            @change="getCatalogID($event)"
          >
            <el-option
              v-for="item in catalogue"
              :key="item.value"
              v-model="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 企业(完成) -->
        <el-form-item
          prop="enterpriseID"
          label="企业:"
        >
          <el-select
            v-model="EnterpriseID"
            placeholder="请选择"
            @change="getEnterpriseID($event)"
          >
            <el-option
              v-for="item in companys"
              :key="item.id"
              v-model="item.company"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 市区联动(完成) -->
        <el-form-item
          prop="city"
          label="城市："
        >
          <el-select
            style="width: 176px"
            v-model="form.province"
            placeholder="请选择"
            @change="change"
            v-on:change="getProv($event)"
          >
            <el-option
              v-for="item in provs"
              :label="item"
              :value="item"
              :key="item"
            >
            </el-option>
          </el-select>
          <el-select
            style="width: 176px"
            v-model="form.city"
            placeholder="请选择"
          >
            <el-option
              v-for="item in citys"
              :label="item"
              :value="item"
              :key="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 方向(完成) -->
        <el-form-item
          prop="firm"
          label="方向:"
        >
          <el-select
            v-model="form.direction"
            placeholder="请选择"
          >
            <el-option
              v-for="item in direction"
              :key="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 题型 -->
        <el-form-item
          prop="questionType"
          label="题型:"
        >
          <el-radio-group v-model="form.questionType">
            <el-radio
              label="1"
              @change="isRadioChange"
            >单选</el-radio>
            <el-radio
              label="2"
              @change="isRadioChange"
            >多选</el-radio>
            <el-radio
              @change="isRadioChange"
              label="3"
            >简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 难度(完成) -->
        <el-form-item
          prop="difficulty"
          label="难度:"
        >
          <el-radio-group v-model="form.difficulty">
            <el-radio label="1">简单</el-radio>
            <el-radio label="2">一般</el-radio>
            <el-radio label="3">困难</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 题干(富文本编辑器)(完成) -->
        <el-form-item
          label="题干:"
          prop="question"
          class="articles_content"
        >
          <quill-editor
            @blur="$refs.form.validateField('question')"
            v-model="form.question"
            :options="editorOption"
          ></quill-editor>
        </el-form-item>
        <!-- 选项(上传图片) -->

        <!-- 上传图片 -->
        <el-form-item
          label="选项："
          v-if="form.questionType !== '3'"
        >
          <!-- 遍历选项输入框 -->
          <div
            class="radioUpload"
            v-for="(item , index) in form.options"
            :key="item.zd"
          >
            <el-radio
              id="radio"
              style="margin-right:0;"
              v-if="isRadio"
              v-model="CODE"
              :label="index"
              @input='getOption'
            >{{arr[item.zd]}}:</el-radio>
            <el-checkbox
              v-model="item.isRight"
              :label="index"
              v-else
            >{{arr[item.zd]}}:</el-checkbox>
            <el-input
              v-model="item.title"
              style="width:19%"
            ></el-input>
            <div class="box2">
              <el-upload
                list-type="picture-card"
                action="#"
                class="uploadImg"
                :http-request="($event)=>httpRequest($event,index)"
                :on-preview="handlePictureCardPreview"
                :file-list="fileList[index]?[{url:fileList[index]}]:FileList"
                :limit="limit"
                :on-exceed="onExceed"
                :before-upload="beforeUpload"
                :on-remove="() => removeImg(index)"
              >
                <span>点击上传图片</span>
              </el-upload>
              <el-dialog
                :visible.sync="dialogVisible"
                title="图片预览"
              >
                <img
                  width="100%"
                  :src="dialogImageUrl"
                  alt=""
                >
              </el-dialog>
              <el-button
                size="small"
                :disabled='index >= 4?false:true'
                @click="delButton(index)"
              >删除</el-button>
            </div>

          </div>
          <el-button
            v-if="disabled"
            type="button"
            style="background-color:#fab6b6;color:#fff;border-color: #fab6b6"
            :disabled="disabled"
          >+增加选项与答案</el-button>
          <el-button
            v-else
            type="danger"
            style="color:#fff;"
            :disabled="disabled"
            @click="addDomConstruction"
          >+增加选项与答案</el-button>

        </el-form-item>

        <!-- 解析视频 -->
        <el-form-item label="解析视频">
          <el-input
            v-model="form.videoURL"
            style="width:353px;"
          ></el-input>
        </el-form-item>
        <!-- 答案解析(富文本编辑器)(完成) -->
        <el-form-item
          label="答案解析:"
          prop="answer"
          class="articles_content"
        >
          <quill-editor
            @blur="$refs.form.validateField('answer')"
            v-model="form.answer"
            :options="editorOption"
          >
          </quill-editor>
        </el-form-item>
        <!-- 题目备注 -->
        <el-form-item label="题目备注:">
          <el-input
            v-model="form.remarks"
            style="width:353px;line-height: 1.5;"
            type="textarea"
          ></el-input>
        </el-form-item>
        <!-- 试题标签 -->
        <el-form-item label="试题标签">
          <el-select
            :filterable="true"
            :allow-create="true"
            v-model="Tags"
            multiple
            placeholder="请选择"
            default-first-option
            @change="geyTags"
          >
            <!--  -->
            <el-option
              v-for="item in tagsList"
              :key="item.value"
              v-model="item.label"
            >
            </el-option>
          </el-select>

        </el-form-item>
        <!-- 提交按钮 -->
        <el-form-item>
          <el-button
            :style="showColor"
            type="primary"
            @click="onSubmit"
          >{{showButton}}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 学科简单列表接口
import { simple as subjects } from '../../api/hmmm/subjects'
// 目录简单列表接口
import { simple } from '../../api/hmmm/directorys'
// 企业简单列表接口
import { list as companyList } from '../../api/hmmm/companys'
// 获取方向
import { direction } from '../../api/hmmm/constants'
// 市区联动
import { provinces, citys } from '../../api/hmmm/citys'
// 标签联动
import { simple as tagsList } from '../../api/hmmm/tags'
// 基础题库添加 //========引入获取试题详情的接口(用于回显)========== // 用于修改
import {
  add,
  detail as getQuestionsInfo,
  update
} from '../../api/hmmm/questions'
// 引入富文本
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

// ==============================上传图片的引入===========================
import cos from '../../utils/cos.js'

export default {
  // 注册富文本
  components: {
    quillEditor
  },
  data () {
    return {
      // 富文本编辑器配置
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            ['blockquote', 'code-block'], // 引用代码块
            ['image', 'link'] // 图片、链接
          ]
        },
        placeholder: ''
      },
      form: {
        // 学科
        subjectID: '',
        // 目录
        catalogID: '',
        // 企业
        enterpriseID: '',
        // 城市
        province: '',
        // 城市子集地区
        city: '',
        // 方向
        direction: '',
        // 题型
        questionType: '',
        // 难度
        difficulty: '',
        // 题干(富文本内容)
        question: '',
        // 按钮
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false,
            zd: 0
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false,
            zd: 1
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false,
            zd: 2
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false,
            zd: 3
          }
        ],

        // 解析视频
        videoURL: '',
        // 答案解析
        answer: '',
        // 题目备注
        remarks: '',
        // 试题标签
        tags: ''
      },
      rules: {
        // 学科
        subjectID: [
          { required: true, message: '请输入学科', trigger: ['blur', 'change'] }
        ],
        // 目录
        catalogID: [
          { required: true, message: '请输入目录', trigger: ['blur', 'change'] }
        ],
        // 企业
        enterpriseID: [
          {
            required: true,
            message: '请选择企业',
            trigger: ['blur', 'change']
          }
        ],
        // 城市
        city: [
          {
            required: true,
            message: '请选择地区',
            trigger: ['blur', 'change']
          }
        ],
        // 题型
        questionType: [
          {
            required: true,
            message: '请选择题型',
            trigger: ['blur', 'change']
          }
        ],
        // 难度
        difficulty: [
          {
            required: true,
            message: '请选择难度',
            trigger: ['blur', 'change']
          }
        ],
        // 题干
        question: [
          { required: true, message: '请输入题干', trigger: ['blur', 'change'] }
        ],
        // 答案解析
        answer: [
          { required: true, message: '请输入答案', trigger: ['blur', 'change'] }
        ]
      },

      // 先定义一个value让下拉菜单不报错
      value: '',
      // 接受学科列表
      subject: [],
      // 接收目录数组
      catalogue: [],
      // 接收企业数组
      companys: [],
      // 接收方向数组
      direction: [],
      // 接受城市列表
      provs: [],
      // 接受城市子集地区列表
      citys: [],
      // 控制单选还是多选
      isRadio: true,
      // 接受标签的数组
      tagsList: [],
      // 控制增加选项与答案按钮
      disabled: '',
      // 为序号设置数据
      zd: 4,
      arr: [
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z'
      ],
      // 用于接受单选传值(做互斥)
      CODE: '',
      // 用于显示学科的名字
      subjectName: '',
      // 用于显示目录的名字
      catalogName: '',
      // 用于显示企业名字
      EnterpriseID: '',
      // 用于接受数组标签
      Tags: [],
      // ===========================上传图片需要的数据===========================
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      FileList: [],
      // 上传的最大数
      limit: 1
      // ============图片回显得数据
      // dialogMode: 'create' // create、edit
    }
  },
  created () {
    // 获取企业简单列表
    this.getCompanysList()
    // 获取基础题库列表
    this.getBaseQuestionBankList()
    // 获取基础题库里的方向列表
    this.getdirectionList()
    // 获取所有城市列表
    this.getCitysList()
  },
  mounted () {
    // ======================调用详情接口回显================
    this.getQuestions()
    // ==============================================================
  },

  computed: {
    // ===========================上传图片用到的计算属性============================

    // ============================================================================
    // 判断使添加还是修改
    showTitle () {
      return this.form.id ? '试题修改' : '试题录入'
    },
    showButton () {
      return this.form.id ? '确认修改' : '确认提交'
    },
    showColor () {
      return this.form.id
        ? 'background-color:#85ce61;'
        : 'background-color:#409eff;'
    }
    // 判断图片形式
    // img () {
    //   return this.form.id ? 'create、edit' : 'create'
    // }
  },
  methods: {
    // 获取基础题库列表
    async getBaseQuestionBankList () {
      const { data: res } = await subjects()
      this.subject = res
    },
    // 获取目录(与学科联动)
    async getSubjectsInfo (val) {
      this.catalogName = ''
      const item = this.subject.filter(item => {
        return item.label === val
      })
      // 获取的学科ID
      const id = item[0].value
      // 把form里的名字换成ID
      this.form.subjectID = id
      const { data: res } = await simple({ subjectID: id })
      this.catalogue = res
      this.getTagsList(id)
    },
    // 获取标签(与学科联动)
    async getTagsList (id) {
      const { data: res } = await tagsList({ subjectID: id })
      this.tagsList = res
    },

    // 获取标签ID
    getCatalogID (val) {
      const item = this.catalogue.filter(item => {
        return item.label === val
      })
      // 获取的目录ID
      const id = item[0].value
      this.form.catalogID = id
    },
    // 将标题数组转为字符串
    geyTags () {
      this.form.tags = this.Tags.join(',')
    },

    // 获取企业简单列表
    async getCompanysList () {
      const { data: res } = await companyList({ pagesize: 1000 })
      this.companys = res.items
    },
    // 获取企业ID
    getEnterpriseID (val) {
      const item = this.companys.filter(item => {
        return item.company === val
      })
      // 获取的企业ID
      this.form.enterpriseID = item[0].id
    },
    // 获取基础题库里的方向列表
    async getdirectionList () {
      this.direction = direction
    },
    // 获取所有城市列表
    getCitysList () {
      const citys = provinces()
      this.provs = citys
    },
    // 选择城市时触发
    getProv (val) {
      this.form.city = ''
      this.citys = citys(val)
    },
    // 点击改变单选或多选
    isRadioChange () {
      if (this.form.questionType === '1') {
        this.form.options.forEach(item => {
          item.isRight = 0
        })
        this.isRadio = true
        this.disabled = true
      } else if (this.form.questionType === '2') {
        this.CODE = ''
        this.isRadio = false
        this.disabled = false
      }
    },
    // 获取选择的选项
    getOption (val) {
      // 点击的单选按钮
      // 调用函数先让每一个选项都变为false
      this.form.options.forEach(item => {
        item.isRight = false
      })
      this.form.options[val].isRight = true
    },
    // 点击增加选项与答案
    addDomConstruction () {
      const zd = this.zd++ + 1
      this.form.options.push({
        zd,
        code: this.arr[zd],
        title: '',
        img: '',
        isRight: false
      })
      if (zd === 25) {
        this.zd = 0
      }
    },
    // 点击删除按钮
    delButton (index) {
      this.form.options.splice(index, 1)
    },
    // 点击提交按钮
    onSubmit () {
      this.$refs.form.validate(async valid => {
        if (!valid) return

        if (this.form.id) {
          await update(this.form)
            .then(res => {
              this.$message.success('修改成功')
              this.$refs.form.resetFields()
              this.form.options.forEach(item => {
                item.img = ''
              })
              this.fileList.forEach(item => {
                item = undefined
              })
              this.$router.push('/questions/list')
            })
            .catch(err => {
              this.$message.error('修改失败,请稍后重试')
              console.log(err)
            })
        } else {
          await add(this.form)
            .then(res => {
              this.$message.success('添加成功')
              this.$refs.form.resetFields()
              this.$router.push('/questions/list')
            })
            .catch(err => {
              this.$message.error('添加失败')
              console.log(err)
            })
        }
        // 初始化表单
        this.form.options = [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false,
            zd: 0
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false,
            zd: 1
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false,
            zd: 2
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false,
            zd: 3
          }
        ]
      })
    },
    // 解决表单验证不生效的问题
    change (val) {
      this.form = { ...this.form }
    },
    // ================================上传图片用到的函数====================================
    /**
     * file:删除的那条数据
     * fileList:剩余的数据
     */
    // 文件列表移除文件时的钩子
    // handleRemove (file, fileList) {
    //   this.
    // },
    // 文件上传时的钩子
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },

    // 达到上限后继续上传图片会执行这个钩子函数
    onExceed () {
      this.$message.warning('上传图片已达最大值')
    },

    // 覆盖默认的上传行为，可以自定义上传的实现
    httpRequest ({ file }, index) {
      // 可以在这里调用云服务接口
      if (!file) return
      // const curFileObj = this.form.options[index].find(
      //   item => item.img === file.uid
      // )
      // // 将状态改为上传中
      // curFileObj.status = 'uploading'
      cos.putObject(
        {
          Bucket: 'awei-1315206379' /* 填入您自己的存储桶，必须字段 */,
          Region: 'ap-beijing' /* 存储桶所在地域，例如ap-beijing，必须字段 */,
          Key:
            +new Date() +
            file.name /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
          Body: file /* 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象 */,
          onProgress: function (progressData) {
            // 可以实时获取上传进度
            // curFileObj.percentage = progressData.percent * 100
          }
        },
        // 上传之后,不管成功还是失败都会执行
        (err, data) => {
          if (err) {
            this.$message.error('上传失败,请稍后再试')
            return
          }
          if (data.statusCode === 200) {
            // 显示对钩
            // curFileObj.status = 'success' // success 是图片加载完成是的状态
            // // 只写//表示的当前这个地址的协议 会自动给你加上当前网站的协议
            // curFileObj.url = '//' + data.Location
            this.form.options[index].img = '//' + data.Location
          }
        }
      )
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    // onChange (file, fileList) {
    //   // this.fileList = [...fileList]

    //   console.log(11, fileList)
    // },
    // 配置上传前的校验, 只要通过校验, 才能进行上传
    beforeUpload (file) {
      // 1. 限制文件类型 file.type
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传的图片格式, 必须是jpg, gif, bmp, png的格式!')
        return false
      }
      // 2. 限制文件大小 file.size
      if (file.size / 1024 / 1024 >= 5) {
        this.$message.error('上传头像过大, 超过了5M, 必须5M以内')
        return false
      }
      return true
    },
    // 删除图片时的钩子
    removeImg (index) {
      this.fileList.splice(index, 1, undefined)
      this.form.options[index].img = ''
    },
    // =============================图片回显的方法=============================

    // ==============================回显的方法=============================
    // 获取试题详情
    async getQuestions () {
      if (this.$route.query.id) {
        const id = this.$route.query.id
        const { data } = await getQuestionsInfo({ id })
        this.form = data
        // 回显学科名
        this.subjectName = this.form.subjectName
        // 回显目录名
        this.catalogName = this.form.directoryName
        // 回显图片
        const list = this.form.options.filter(item => {
          return item.img !== '' ? item.img : { img: undefined }
        })
        for (let i = 0; i < list.length; i++) {
          this.fileList.unshift(list[i].img ? list[i].img : undefined)
        }
        // 重新定义zd
        this.form.options.forEach((item, index) => {
          return (item.zd = index)
        })
        if (this.form.questionType === '1') {
          const radio = this.form.options.filter(item => item.isRight === 1)
          // 有可能会有没选正确答案的题
          if (radio.length > 0) {
            this.CODE = radio[0].isRight
          }
        }
        // ==============多选和单选================
        // 调用函数显示单选框还是多选框
        this.isRadioChange()
        // 遍历isRight(多选的回显)
        const checks = this.form.options.filter(item => {
          return item.isRight === 1
        })
        checks.forEach(item => {
          return (item.isRight = true)
        })
        // 回显标签
        this.Tags = this.form.tags?.split(',')
        // 回显企业名
        const companyName = this.companys.filter(item => {
          return item.id === this.form.enterpriseID
        })
        this.EnterpriseID = companyName[0]?.company
        return true
      }
      return false
    }
  }
}
</script>

<style scoped lang='scss'>
.el-card {
  margin: 20px;
  box-sizing: border-box;
  .el-form {
    padding: 0 0 0 30px;
    .el-form-item {
      .el-select {
        width: 353px;
      }
      .radioUpload {
        display: flex;
        position: relative;
        margin-bottom: 30px;
        .el-icon-circle-close {
          position: absolute;
          transform: translate(400%, -95%);
          font-size: 20px;
        }
        .uploadImg {
          width: 120px;
          height: 60px;
          border-radius: 5px;
          border: 1px dashed #ccc;
          margin-left: 5px;
          text-align: center;
          padding-top: 10px;
          margin-top: -10px;
        }
      }
    }
    .articles_content {
      height: 235px;

      .quill-editor {
        height: 235px;
        ::v-deep .ql-toolbar {
          padding: 0;
        }
        ::v-deep .ql-container {
          height: 170px;
        }
      }
    }
  }
}
</style>
<style >
#radio {
  padding-top: 11px;
}
.box2 {
  position: relative;
  width: 123px;
  height: 60px;
}
.uploadImg span {
  font-weight: 600;
  user-select: none;
  height: 16px;
}

.uploadImg .el-upload--picture-card {
  /* opacity: 0; */
  position: absolute;
  width: 123px;
  height: 60px;
  top: -10px;
  left: 5px;
}

.el-upload-list--picture-card .el-upload-list__item {
  position: absolute;
  width: 123px;
  height: 60px;
  top: -11px;
  left: 5px;
  z-index: 9;
}
.box2 .el-button {
  position: absolute;
  top: 1px;
  left: 150px;
}
</style>
